<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VSelect v-model="form.country" placeholder="国家" :options="options.country || []" multiple collapse-tags
          filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.warehouse_id" placeholder="备货仓库" :options="options.warehouse_id" multiple collapse-tags
          filterable clearable style="min-width: 200px" />
        <VSelect v-model="form.promotion_config_id" placeholder="活动类型" :options="options.typeOptions" multiple
          collapse-tags filterable clearable style="min-width: 200px" />
        <VSelect v-model="form.audit_status" placeholder="审核状态" :options="options.audit_status" multiple collapse-tags
          filterable clearable style="min-width: 120px" />
        <VCascader v-model="form.create_user_id" placeholder="申请人" multiple collapse-tags filterable clearable
          style="min-width: 160px" />
        <VGroup>
          <VSelect v-model="form.dateRange.type"
            :options="[{ label: '申请时间', value: 'create_time' }, { label: '审核时间', value: 'audit_time' }]"
            style="width: 110px">
          </VSelect>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/demand/promotion/add" type="primary" @click="handleRow('add')"><i class="dk-iconfont icon-Plus" />添加</VButton>
        <VButton auth="/purchase/demand/promotion/submit" :loading="loadings.change1" @click="handleBatch('submit')">
          批量提交审核</VButton>
        <VAudit auth="/purchase/demand/promotion/examine" field="pd_id"
          url="/v1/purchase-demand/promotion-demand/batch-audit" :tableRef="tableRef"
          @success="query" />
        <VButton auth="/purchase/demand/promotion/create_plan" type="primary" :loading="loadings.change1"
          @click="handleBatch('applyDemand')">创建多平台备货计划</VButton>
        <VButton auth="/purchase/demand/promotion/void" :loading="loadings.change1" @click="handleBatch('cancel')">批量作废
        </VButton>
        <VButton auth="/purchase/demand/promotion/activity_type_configuration" :loading="loadings.change1" class="ml-auto"
          @click="() => typeListRef.open()">活动类型配置</VButton>
        <VExport auth="/purchase/demand/promotion/derive" name="promotion_demand" mainKey="pd_id" :tableRef="tableRef"
          task />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <Edit ref="editRef" :options="options" @success="query" />
    <TypeList ref="typeListRef" :options="options" />
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import Edit from './components/Edit'
import TypeList from './components/TypeList'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { resSkip } from "@/utils/res";

const baseName = 'promotion_demand'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: 'purchase_demand' }).then(res => res.data),
  getOption({ type: 'promotion_config' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
  api.getPromotionConfig().then(res => ({ typeOptions: res.data })),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const typeListRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const pd_ids = selection.map(d => d.pd_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    applyDemand: (is_skip = 1) => {
      showLoading()
      api.applyDemand({ pd_ids, is_skip }).then(res => {
        resSkip({
          res,
          closeLoading,
          success: query,
          submit: () => {
            handle.applyDemand(2)
          },
        })
      }).finally(closeLoading)
    },
    submit: () => {
      showLoading()
      api.batchSubmit({ pd_ids }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    cancel: () => {
      showLoading()
      api.batchCancel({ pd_ids }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
  }
  handle[name]()
}
// 单行操作
const addRef = ref()
const editRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { pd_id } = row || {}
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    add: () => {
      addRef?.value.open()
    },
    edit: () => {
      editRef?.value.open(pd_id)
    },
    submit: () => {
      showLoading()
      api.batchSubmit({ pd_ids: [pd_id] }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    cancel: () => {
      showLoading()
      api.batchCancel({ pd_ids: [pd_id] }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, pd_id })
    }
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  showHeaderOverflow: false,
  rowConfig: { height: 112 },
  formConfig: {
    data: {
      dateRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', with: 40 },
    {
      field: 'sku', title: 'sku', minWidth: 200, slots: {
        default: ({ row }) => <VText value={row.sku} copy></VText>
      }
    },
    { field: 'sku_cn_title', title: '产品名称', minWidth: 160, line: 3 },
    { field: 'country_name', title: '国家', minWidth: 140, line: 2 },
    { field: 'warehouse_name', title: '备货仓库', minWidth: 120, line: 2 },
    { field: 'promotion_name', title: '活动类型', minWidth: 140, line: 2 },
    { field: 'demand_num', title: '需求数量', minWidth: 80 },
    { field: 'demand_delivery_time', title: '需求到货日期', minWidth: 120 },
    {
      field: 'demand_delivery_time', title: '备货计划信息', minWidth: 240, slots: {
        default: ({ row, rowIndex }) => {
          return <div>
            <VText value={row.apply_demand_status_name} />
            <VMore key={rowIndex}>
              {{
                default: (line) => (row.demand || []).map(d => <div class='w-full'>
                  <VText title='备货计划单号' value={d.demand_no} line={line} />
                  <VText title='已下单数量' value={d.demand_num} line={line} />
                  <VText title='备库需求单状态' value={d.demand_status_name} line={line} />
                </div>)
              }}
            </VMore>
          </div>
        }
      }
    },
    { field: 'remark', title: '备注', minWidth: 120, line: 3 },
    { field: 'audit_status_name', title: '审核状态', minWidth: 120, line: 2 },
    {
      minWidth: 180, slots: {
        header: () => <div>申请人<br />申请部门<br />申请时间</div>,
        default: ({ row }) => <div>
          <VText value={row.create_user}></VText>
          <VText value={row.department_name} line={1} />
          <VText value={row.create_time}></VText>
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>审核人<br />审核日期</div>,
        default: ({ row }) => <div>
          <VText value={row.audit_user_name}></VText>
          <VText value={row.audit_time}></VText>
        </div>
      }
    },
    {
      field: 'audit_remark', title: '驳回原因', minWidth: 120, line: 3
    },
    {
      title: '操作', width: 100, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { audit_status } = row
          // 审核状态 1待提交 2待审核 3已审核 4已驳回 5已作废
          return <div class='nm flex flex-wrap'>
            {[1, 4].includes(audit_status) ? <VButton auth="/purchase/demand/promotion/submit" link type="primary" onClick={() => handleRow('submit', row, rowIndex)}>提交</VButton> : ''}
            {[1, 4].includes(audit_status) ? <VButton auth="/purchase/demand/promotion/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton> : ''}
            {[1, 4].includes(audit_status) ? <VButton auth="/purchase/demand/promotion/cancel" link type="primary" onClick={() => handleRow('cancel', row)}>作废</VButton> : ''}
            <VButton auth="/purchase/demand/promotion/logs" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  